package com.yjf.ljr.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.adapter.CommonAdapter;
import com.yjf.ljr.adapter.CommonAdapter.HandleCallBack;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.AddBankDataClass;
import com.yjf.ljr.dataclass.AddBankDataClass.AddBankInfo;
import com.yjf.ljr.dataclass.EasyDataClass;
import com.yjf.ljr.dataclass.VerifySmsCodeDataClass;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.util.AppUtil.HandlerItemCallBack;
import com.yjf.ljr.util.MyImageDownload;

public class AddBankCardActivity extends IjActivity implements OnClickListener {

	@ID("llAddBank")
	private LinearLayout mLlAddBank;
	@ID("btAddBank")
	private Button mBtAddBank;// 添加银行卡按钮
	@ID("ivBankLogoUrl")
	private ImageView mIvBankLogoUrl;// 银行图标
	@ID("tvChoiceBank")
	private TextView mTvChoiceBank;

	@ID("etBankNumber")
	private EditText mEtBankNumber;// 银行卡号
	@ID("etPhoneNumber")
	private EditText mEtPhoneNumber;// 手机号码
	@ID("etcodemessage")
	private EditText mEtCodeMessage;// 验证码
	@ID("btsend")
	private Button mBtSend;// 发送验证码
	@ID("tvBankAccountName")
	private TextView mTvBankAccountName;// 账户主姓名

	private AddBankInfo selectedBankInfo;

	private TimeCount time;// 计时

	private List<AddBankInfo> mDataBank = new ArrayList<AddBankInfo>();
	private String[] mArrBanK = new String[] { "中国银行", "中国建设银行", "华夏银行", "中国农业银行", "中国工商银行", "徽商银行" };
	private List<AddBankInfo> mBankInfos = new ArrayList<AddBankInfo>();

	private boolean isGetCode = false;

	private PopupWindow popMenu;
	private CommonAdapter adapter;

	private MyImageDownload imageDownLoad;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_bank);
		initControl();
		isGetCode = false;
		String mPath = "";
		if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {
			mPath = CommonData.IMAMGE_DIR_SD + "/";
		} else {
			mPath = CommonData.IMAMGE_DIR_RAM + "/";
		}
		imageDownLoad = new MyImageDownload(false, mPath);
	}

	private void initControl() {
		setLeftBtnClick();
		setTitleStr("添加银行卡");
		mLlAddBank.setOnClickListener(this);
		mBtSend.setOnClickListener(this);
		mBtAddBank.setOnClickListener(this);
		time = new TimeCount(60000, 1000);
		String realName = getIntent().getStringExtra("realName");// 真实姓名
		if (!TextUtils.isEmpty(realName) && realName.length() > 0) {
			mTvBankAccountName
					.setText(getString(R.string.add_bank_card_account_name, realName.subSequence(0, 1) + "**"));
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.llAddBank:
			if (mBankInfos.size() == 0) {
				showProgressDialog();
				new ObtainBankAddressTask().execute();
			} else {
				if (adapter == null || popMenu == null) {
					adapter = new CommonAdapter(AddBankCardActivity.this, mBankInfos, R.layout.item_text_popmenu,
							ViewHolder.class, mHandleCallBackBank);
					popMenu = AppUtil.getPopupWindow(mContext, adapter, "请选择银行", new HandlerItemCallBack() {

						@Override
						public void handle(AdapterView<?> parent, View view, int position, long id) {
							// TODO Auto-generated method stub
							AddBankInfo infos = mBankInfos.get(position);
							selectedBankInfo = infos;
							mTvChoiceBank.setText(infos.bankName);
							mIvBankLogoUrl.setVisibility(View.VISIBLE);
							imageDownLoad.download(infos.bankLogo, mIvBankLogoUrl);
						}
					});

				}
				adapter.notifyDataSetChanged();
				popMenu.showAtLocation(mLlAddBank, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
			}
			break;
		case R.id.btsend:// 发送验证码
			String bankCardNo = mEtBankNumber.getText().toString().trim();
			String mobileNum = mEtPhoneNumber.getText().toString().trim();

			if (selectedBankInfo == null) {
				showToast("请选择银行");
				return;
			}
			if (TextUtils.isEmpty(bankCardNo)) {
				showToast("请输入银行卡号码");
				return;
			}
			if (TextUtils.isEmpty(mobileNum)) {
				showToast("请输入银行预留的手机号码");
				return;
			} else if (!isMobileNO(mobileNum)) {
				showToast("请输入正确的手机号码");
				return;
			}
			showProgressDialog();
			new CheckBankCard(bankCardNo, selectedBankInfo.bankCode).execute();
			time.start();
			break;
		case R.id.btAddBank:// 绑定银行卡
			if (selectedBankInfo == null) {
				showToast("请选择银行");
				return;
			}
			String bankCardNo1 = mEtBankNumber.getText().toString().trim();
			if (TextUtils.isEmpty(bankCardNo1)) {
				showToast("请输入银行卡号码");
				return;
			}
			String mobile = mEtPhoneNumber.getText().toString().trim();
			if (TextUtils.isEmpty(mobile)) {
				showToast("请输入银行预留的手机号码");
				return;
			} else if (!isMobileNO(mobile)) {
				showToast("请输入正确的手机号码");
				return;
			}
			if (!isGetCode) {
				showToast("请获取验证码");
				return;
			}
			String mobileCode = mEtCodeMessage.getText().toString().trim();
			if (TextUtils.isEmpty(mobileCode)) {
				showToast("请输入手机验证码");
				return;
			}
			showProgressDialog();
			new VerifyCodeMessage(mobileCode).execute();
			break;
		default:
			break;
		}
	}

	class ObtainBankAddressTask extends AsyncTask<Void, Void, String> {
		AddBankDataClass dc = new AddBankDataClass();

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... arg0) {
			RequestObject mObject = new RequestObject();
			mObject.method = "getAvalSinBank";
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			dismissProgressDialog();
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(result)) {// fail
				showToast(result);
			} else {// success
				mBankInfos.clear();
				mBankInfos.addAll(dc.singBankList);

				if (adapter == null || popMenu == null) {
					adapter = new CommonAdapter(AddBankCardActivity.this, mBankInfos, R.layout.item_text_popmenu,
							ViewHolder.class, mHandleCallBackBank);
					popMenu = AppUtil.getPopupWindow(mContext, adapter, "请选择银行", new HandlerItemCallBack() {

						@Override
						public void handle(AdapterView<?> parent, View view, int position, long id) {
							AddBankInfo infos = mBankInfos.get(position);
							mTvChoiceBank.setText(infos.bankName);
							selectedBankInfo = infos;
							mIvBankLogoUrl.setVisibility(View.VISIBLE);
							imageDownLoad.download(infos.bankLogo, mIvBankLogoUrl);
						}
					});
				}
				adapter.notifyDataSetChanged();
				popMenu.showAtLocation(mLlAddBank, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
			}
		}
	}

	// 判断手机格式是否正确
	public boolean isMobileNO(String mobiles) {
		// Pattern p =
		// Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	private HandleCallBack mHandleCallBackBank = new HandleCallBack() {

		@SuppressWarnings("unchecked")
		@Override
		public void handle(int position, View convertView, ViewGroup parent, Object holder, Object item) {
			// TODO Auto-generated method stub
			final ViewHolder v = (ViewHolder) holder;
			AddBankInfo info = (AddBankInfo) item;
			v.tvBankName.setText(info.bankName);
			imageDownLoad.download(info.bankLogo, v.ivBankLogo);
		}

	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (imageDownLoad != null) {
			imageDownLoad.clearCache();
		}
	}

	public static class ViewHolder {

		TextView tvBankName;
		TextView tvBankAdress;
		ImageView ivBankLogo;

	}

	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			mBtSend.setText("重新发送");
			mBtSend.setClickable(true);
		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			mBtSend.setClickable(false);
			mBtSend.setText(millisUntilFinished / 1000 + "秒");
		}
	}

	/******** 验证短信验证码是否正确 ******/
	class VerifySmsCodeTask extends AsyncTask<Void, Void, String> {
		private String mobile;// 手机号码
		private String code;// 验证码
		private VerifySmsCodeDataClass dc = new VerifySmsCodeDataClass();

		public VerifySmsCodeTask(String mobile, String code) {
			this.mobile = mobile;
			this.code = code;
		}

		@Override
		protected String doInBackground(Void... params) {
			RequestObject mObject = new RequestObject();
			mObject.method = "verifySmsCode";
			mObject.map.put("mobile", mobile);
			mObject.map.put("code", code);
			mObject.map.put("business", "cellphone");// 这个需要修改，现在还没这个状态的字段
			// TODO Auto-generated method stub
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}
			dismissProgressDialog();
			if (!TextUtils.isEmpty(result)) {// fail
				showToast(result);

			} else {// success

			}
		}
	}

	class CheckBankCard extends AsyncTask<Void, Void, String> {

		private String bankCardNo;// 手机号码
		private String bankCode;// 验证码
		private EasyDataClass dc = new EasyDataClass();

		public CheckBankCard(String bankCardNo, String bankCode) {
			this.bankCardNo = bankCardNo;
			this.bankCode = bankCode;
		}

		@Override
		protected String doInBackground(Void... params) {
			RequestObject mObject = new RequestObject();
			mObject.method = "checkBankCard";
			mObject.map.put("bankCardNo", bankCardNo);
			mObject.map.put("bankCode", bankCode);
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if ("-1".equals(dc.code)) {
				dismissProgressDialog();
				time.cancel();
				time.onFinish();
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(result)) {// fail
				dismissProgressDialog();
				showToast(result);
				time.cancel();
				time.onFinish();
			} else {
				String bankCardNo = mEtBankNumber.getText().toString().trim();
				String mobileNum = mEtPhoneNumber.getText().toString().trim();
				new SingBank(bankCardNo, mobileNum).execute();
			}
		}
	}

	class VerifyCodeMessage extends AsyncTask<Void, Void, String> {

		private String mobileCode;// 短信验证码
		private EasyDataClass dc = new EasyDataClass();

		public VerifyCodeMessage(String mobileCode) {
			this.mobileCode = mobileCode;
		}

		@Override
		protected String doInBackground(Void... params) {
			RequestObject mObject = new RequestObject();
			mObject.method = "singBankCheck";
			mObject.map.put("mobileCode", mobileCode);
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			dismissProgressDialog();
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(result)) {// fail
				showToast(result);
			} else {
				showToast(dc.msg);
				setResult(RESULT_OK);
				finish();
			}
		}

	}

	class SingBank extends AsyncTask<Void, Void, String> {

		private String bankCardNo;// 银行号码
		private String phoneNo;// 预留手机号码
		private EasyDataClass dc = new EasyDataClass();

		public SingBank(String bankCardNo, String phoneNo) {
			this.bankCardNo = bankCardNo;
			this.phoneNo = phoneNo;
		}

		@Override
		protected String doInBackground(Void... params) {
			RequestObject mObject = new RequestObject();
			mObject.method = "singBank";
			mObject.map.put("cardNo", bankCardNo);
			mObject.map.put("userPhoneNo", phoneNo);
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			dismissProgressDialog();
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(result)) {// fail
				showToast(result);
			} else {
				showToast("发送验证码成功！");
				isGetCode = true;
				mLlAddBank.setEnabled(false);
				mEtBankNumber.setEnabled(false);
				mEtPhoneNumber.setEnabled(false);
			}
		}
	}

}
